#include "db.h"
#include <stdio.h>
#include <assert.h>
#include <mysql.h>
#include <string.h>
#include <glib.h>

char dbhost[255] = "localhost";
char dbname[255] = "gamebrowser";
char dbuser[255] = "mosca";
char dbpass[255] = "";

int db_setConfig(const char *_dbhost, const char *_dbuser, const char *_dbpass, const char *_dbname)
{
	if(_dbhost)
		strncpy(dbhost, _dbhost, 255);
	if(_dbname)
		strncpy(dbname, _dbname, 255);
	if(_dbuser)
		strncpy(dbuser, _dbuser, 255);
	if(_dbpass)
		strncpy(dbpass, _dbpass, 255);
	return 0;
}

int db_close(MYSQL *conn)
{
	mysql_close(conn);
	conn = NULL;
	return 0;
}

int db_connect(MYSQL *conn)
{
	int timeout = 5;
	my_bool reconnect = 1;

	mysql_init(conn);
	mysql_options(conn, MYSQL_OPT_CONNECT_TIMEOUT, (const char*)&timeout);
	mysql_options(conn, MYSQL_OPT_RECONNECT, &reconnect);

	if(mysql_real_connect(conn, dbhost, dbuser, dbpass, dbname, 0, NULL, MYSQL_OPT_COMPRESS)== NULL) {
		fprintf(stderr, "MYSQL: %s\n", mysql_error(conn));
		mysql_close(conn);
		return -1;
	}
	return 0;
}

MYSQL_RES *db_doSql(MYSQL *conn, const char *sql)
{
	int r;
	//mysql_ping(conn);
	assert(conn);
	if((r = mysql_query(conn, sql))) {
		fprintf(stderr, "MYSQL: [%i]: %s\n", r, mysql_error(conn));
		return NULL;
	}
	return mysql_store_result(conn);
}

char *db_escape(MYSQL *conn, const char *str)
{
	char *escStr;
	size_t str_len;

	str_len = strlen(str);

	escStr = g_malloc((str_len * 2) + 1);
	mysql_real_escape_string(conn, escStr, str, str_len);
	//mysql_escape_string(escStr, str, str_len);
	return escStr;
}
